package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtil {

    private static String driverName = "com.mysql.jdbc.Driver";// jdbc4.0以后不需要
    private static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK";
    private static String userName = "root";
    private static String password = "123456";

    public static void registerDriver() {
        try {
            Class.forName(driverName);// jdbc4.0以前需要这句进行驱动注册
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("找不到驱动");
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection conn = null;
        System.out.println("正在连接数据库...");
        conn = DriverManager.getConnection(url, userName, password);
        System.out.println("数据库已连接!");
        return conn;

    }

    public static void closeConnection(Connection conn) {
        System.out.println("正在释放所有资源...");

        if (conn != null) {
            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    /*
     * 释放所有资源
     */
    public static void realeaseAll(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
                st = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        closeConnection(conn);
    }
    public static void main(String[] args) {
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        String sql = "select * from login";// 表中有user_name,user_pw列
        try {
            conn = JDBCUtil.getConnection();
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while (rs.next()) {
                String userName = rs.getString("user_name");
                String passWord = rs.getString("user_pw");
                System.out.format("该记录的账号=%s,密码=%s\n",userName,passWord);
            }
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.realeaseAll(rs, stat, conn);
        }

    }

}
